package com.testing.class14;

import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @Classname CookieStoreTest
 * @Description 类型说明
 * @Date 2022/11/4 20:50
 * @Created by 特斯汀Roy
 */
public class CookieStoreTest {

    public static void main(String[] args) throws IOException {
        //一个公用的cookieStore
        CookieStore purse=new BasicCookieStore();
        CloseableHttpClient roy = HttpClients.custom().setDefaultCookieStore(purse).build();
        //roy登录
        HttpPost login=new HttpPost("http://localhost:9090/user/login");
        StringEntity loginParam=new StringEntity("username=will&password=123456","utf-8");
        loginParam.setContentType("application/x-www-form-urlencoded");
        loginParam.setContentEncoding("utf-8");
        login.setEntity(loginParam);
        String royLogin = EntityUtils.toString(roy.execute(login).getEntity(), "utf-8");
        System.out.println("roy登录的结果是："+royLogin);

        //roy获取用户
        HttpGet getUser=new HttpGet("http://localhost:9090/user/getUser");
        String royGetUser = EntityUtils.toString(roy.execute(getUser).getEntity(), "utf-8");
        System.out.println("roy获取用户信息的结果是："+royGetUser);


        //will去获取用户
        CloseableHttpClient will = HttpClients.custom().build();
        String willGetUser = EntityUtils.toString(will.execute(getUser).getEntity(), "utf-8");
        System.out.println("will获取用户新的结果是"+willGetUser);


        //royWife获取。
        CloseableHttpClient royWife = HttpClients.custom().setDefaultCookieStore(purse).build();
        String royWifeGetUser = EntityUtils.toString(royWife.execute(getUser).getEntity(), "utf-8");
        System.out.println("royWife获取用户的结果是"+royWifeGetUser);

        System.out.println(purse);
        System.out.println(purse.getCookies());
    }

}
